#define UNICODE
#define _UNICODE

#include <iostream>
#include <xmllite.h>
#include <shlwapi.h>
#include <comdef.h>

#pragma comment( lib, "xmllite.lib")
#pragma comment( lib, "shlwapi.lib")

_COM_SMARTPTR_TYPEDEF(IStream, __uuidof(IStream));
_COM_SMARTPTR_TYPEDEF(IXmlReader, __uuidof(IXmlReader));
_COM_SMARTPTR_TYPEDEF(IXmlWriter, __uuidof(IXmlWriter));

int wmain( int argc, wchar_t* argv[])
{
	HRESULT hr;
	if( ( argc < 2) || ( argc > 3))
	{
		std::wcout << L"Usage: " << argv[0] << L"<xml_file_name>" << std::endl;
		return 0;
	}

	IStreamPtr pFileStream;
	if( FAILED( hr = SHCreateStreamOnFile( argv[1], STGM_READ, &pFileStream)))
	{
		std::wcout << L"Error creating file reader, error is " << hr;
		return 0;
	}

	IXmlReaderPtr pReader;
	if( FAILED( hr = CreateXmlReader( __uuidof( IXmlReader), ( void**) &pReader, NULL)))
	{
		std::wcout << L"Error xml reader, error is " << hr;
		return 0;
	}

	if( FAILED( hr = pReader->SetInput( pFileStream)))
	{
		std::wcout << L"Error setting input for reader, error is" << hr;
		return 0;
	}

	// Writing
	DWORD dwFlags = STGM_CREATE | STGM_WRITE;
	wchar_t* pszOutFileName = argv[2];
	if( argc == 2)
	{
		dwFlags = dwFlags & ~STGM_CREATE;
		pszOutFileName = L"CON";
	}

	IStreamPtr pOutFileStream;
	if( FAILED( hr = SHCreateStreamOnFile( pszOutFileName, dwFlags, &pOutFileStream)))
	{
		std::wcout << L"Error creating file writer, error is" << hr;
		return 0;
	}

	IXmlWriterPtr pWriter;
	if( FAILED( hr = CreateXmlWriter( __uuidof( IXmlWriter), ( void**) &pWriter, NULL)))
	{
		std::wcout << L"Error creating xml writer, error is " << hr;
		return 0;
	}

	if( FAILED( hr = pWriter->SetOutput( pOutFileStream)))
	{
		std::wcout << L"Error, Method: SetOutput, error is " << hr;
		return 0;
	}

	if( FAILED( hr = pWriter->SetProperty( XmlWriterProperty_Indent, TRUE)))
	{
		std::wcout << L"Error, Method: SetProperty XmlWriterProperty_Indent, error is " << hr;
		return 0;
	}

	pWriter->WriteNode( pReader, FALSE);
	return 0;
}
